package com.example.himalaya.ui;


import android.animation.ValueAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.R;
import com.example.himalaya.adapters.PlayerTrackPagerAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.interfaces.IPlayerCallback;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.utils.LogUtils;
import com.example.himalaya.views.SobPopWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

public class PlayerActivity extends BaseActivity implements IPlayerCallback {

    private String TAG = "PlayerActivity";
    private ImageView mControlBtn;
    private PlayerPresenter mPlayerPresenter;
    private boolean status = false;
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("HH:mm:ss");
    private SimpleDateFormat mMinFormat = new SimpleDateFormat(" mm:ss");
    private String totalDuration;
    private TextView mTotalDuration;
    private String currentPosition;
    private TextView mCurrentPosition;
    private SeekBar mMSeekBar;
    private boolean mIsUserTouchProgressBar = false;
    private int mCurrentProgress = 0;
    private boolean mUserCollter = false;
    private ImageView mPlayPro;
    private ImageView mPlayNext;
    private TextView mTrackTitle;
    private String mTrackTitletemp;
    private int mPlayIndex = 0;
    private ViewPager mTrackCover;
    private PlayerTrackPagerAdapter mTrackPagerAdapter;
    private boolean mIsUserSlidePage = false;
    private ImageView mSwitchModel;
    private static Map<PlayMode, PlayMode> sModeMap = new HashMap();

    static {
        // 列表播放 PLAY_MODEL_LIST---》
        // 列表循环 PLAY_MODEL_LIST_LOOP---》
        // 随机播放 PLAY_MODEL_RANDOM ---》
        // 单曲播放 PLAY_MODEL_SINGLE---》
        // 单曲循环 PLAY_MODEL_SINGLE_LOOP
        sModeMap.clear();
        sModeMap.put(PLAY_MODEL_LIST, PLAY_MODEL_LIST_LOOP);
        sModeMap.put(PLAY_MODEL_LIST_LOOP, PLAY_MODEL_RANDOM);
        sModeMap.put(PLAY_MODEL_RANDOM, PLAY_MODEL_SINGLE);
        sModeMap.put(PLAY_MODEL_SINGLE, PLAY_MODEL_SINGLE_LOOP);
        sModeMap.put(PLAY_MODEL_SINGLE_LOOP, PLAY_MODEL_LIST);
    }

    private PlayMode mCurrentModel = PLAY_MODEL_LIST;
    private ImageView mPlayerListbtn;
    private SobPopWindow mSobPopWindow;
    private ValueAnimator mEnterBgAnimator;
    private float mValue;
    private ValueAnimator mExitBgAnimator;

    private final int BG_ANIMATION_DURATION =500;


    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        //测试播放
//        LogUtils.d(TAG,"测试播放");
//        playerPresenter.play();

        initView();
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);
        mPlayerPresenter.getPlayList();
        initEvent();
        initBgAnimation();

    }

    private void initBgAnimation() {
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f, 0.5f);
        mEnterBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mValue = (float) animation.getAnimatedValue();
                upDateBgAlphe(mValue);
                LogUtils.d(TAG, "***LY*** " + animation.getDuration() + animation.getAnimatedValue());
            }
        });

        mExitBgAnimator = ValueAnimator.ofFloat(0.5f,1.0f);
        mExitBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mExitBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mValue = (float) animation.getAnimatedValue();
                upDateBgAlphe(mValue);
                LogUtils.d(TAG, "***LY2*** " + animation.getDuration() + animation.getAnimatedValue());

            }
        });

    }


    private void initView() {
        mControlBtn = findViewById(R.id.play_or_pause);
        mCurrentPosition = findViewById(R.id.current_position);
        mTotalDuration = findViewById(R.id.track_duration);
        mMSeekBar = findViewById(R.id.track_seek_bar);
        mHourFormat.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        mMinFormat.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        mPlayPro = findViewById(R.id.play_pre);
        mPlayNext = findViewById(R.id.play_next);
        mTrackTitle = findViewById(R.id.track_title);
        mTrackCover = findViewById(R.id.track_cover);
        mTrackCover.setOffscreenPageLimit(5);

        mSwitchModel = findViewById(R.id.player_model_switch_btn);
        mPlayerListbtn = findViewById(R.id.play_list);

        mSobPopWindow = new SobPopWindow();
//        LogUtils.d(TAG,"*************title----->"+mTrackTitletemp);
        if (!TextUtils.isEmpty(mTrackTitletemp)) {
            mTrackTitle.setText(mTrackTitletemp);
        }

//        创建适配器
        mTrackPagerAdapter = new PlayerTrackPagerAdapter();
//         设置适配器
        mTrackCover.setAdapter(mTrackPagerAdapter);

    }

    /**
     * 给控件设置相关事件
     */
    private void initEvent() {
        //播放按键
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter.isPlay()) {
                    mPlayerPresenter.pause();
                    mPlayerPresenter.onPlayPause();
                } else {
                    mPlayerPresenter.play();
                    mPlayerPresenter.onPlayStart();
                }
            }
        });
        //进度条
        mMSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            /**
             * @param seekBar
             * @param progress  进度
             * @param fromUser  是否是用户触摸
             */
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mCurrentProgress = progress;
                    //拖动seekbar条
                    setCurrentProgress(seekBar.getProgress(), false);
                    LogUtils.d(TAG, "seekbarprogress  :" + seekBar.getProgress() + "");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //手按下进度条时
                mIsUserTouchProgressBar = true;
                mUserCollter = true;

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //  手离开进度条时
                mPlayerPresenter.seekTo(mCurrentProgress);
                mIsUserTouchProgressBar = false;
                mUserCollter = false;

            }
        });

        //上一首
        mPlayPro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayerPresenter.playPre();
            }
        });

        //下一首
        mPlayNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayerPresenter.playNext();
            }
        });


        mTrackCover.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                LogUtils.d(TAG, "position---（1）>" + position);
                //当页面选中的时候
                if (mPlayerPresenter != null && mIsUserSlidePage) {
                    mPlayerPresenter.playByIndex(position);
                    LogUtils.d(TAG, "position---（2）>" + position + "   Index   " + mPlayIndex + "    mIsUserSlidePage   " + mIsUserSlidePage);

                }
                mIsUserSlidePage = false;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTrackCover.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePage = true;
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        mSwitchModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchPlayMode();
            }
        });

        mPlayerListbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //展示播放列表
                mSobPopWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                mEnterBgAnimator.start();
                //设置透明度
//                upDateBgAlphe(0.5f);
                //修改背景透明度 有一个渐变的过程
            }
        });
        mSobPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                upDateBgAlphe(1.0f);
                mExitBgAnimator.start();

            }
        });

        mSobPopWindow.setPlayListItemClickListener(new SobPopWindow.PlayListItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mPlayerPresenter.playByIndex(position);
            }
        });
        mSobPopWindow.setPlayListActionClickListener(new SobPopWindow.playListActionClickListener() {
            @Override
            public void onPlayModeClick() {
//切换模式
                switchPlayMode();
            }

            @Override
            public void onOrderClick() {
//切换正逆序
                testOrder=!testOrder;
//                Toast.makeText(PlayerActivity.this,"点击了切换顺序",Toast.LENGTH_SHORT).show();
                mSobPopWindow.updateOrderIcon(!testOrder);
            }
        });
    }
    private boolean testOrder =false;

    private void switchPlayMode() {
        //处理播放模式的切换
        //1.默认列表播放  PLAY_MODEL_LIST

        //根据当前mode获取到下一个mode
        PlayMode mode = sModeMap.get(mCurrentModel);
        //修改播放模式
        LogUtils.d(TAG, "mode--->" + mode);
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(mode);
        }
    }

    public void upDateBgAlphe(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }


    //根據當前播放模式创建状态图标
    private void updatePlayModeBtnImg() {
        int resId = R.drawable.selector_mode_list;
        switch (mCurrentModel) {
            case PLAY_MODEL_LIST:
                resId = R.drawable.selector_mode_list;
                break;
            case PLAY_MODEL_SINGLE:
                resId = R.drawable.selector_mode_single;
                break;
            case PLAY_MODEL_RANDOM:
                resId = R.drawable.selector_mode_random;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resId = R.drawable.selector_mode_list_loop;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId = R.drawable.selector_mode_single_loop;
                break;
        }
        mSwitchModel.setImageResource(resId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayerPresenter.unRegisterViewCallback(this);
    }

    //******************************重写方法***************************

    /**
     * 开始播放
     */
    @Override
    public void onPlayerStart() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.drawable.selector_player_play);

        }
    }

    /**
     * 暂停播放
     */
    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.drawable.selector_player_stop);
        }
    }

    /**
     * 停止播放
     */
    @Override
    public void onPlayStop() {

    }

    /**
     * 播放出错
     */
    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    /**
     * 列表加载
     *
     * @param list 播放器列表数据
     */
    @Override
    public void onListLoaded(List<Track> list) {
//        LogUtils.d(TAG, "list -------------->" );
        if (mTrackPagerAdapter != null) {
            mTrackPagerAdapter.setData(list);
        }
        //获取数据后给播放列表发送一份
        mSobPopWindow.setListData(list);
    }

    /**
     * 播放模式转换
     *
     * @param playMode
     */
    @Override
    public void onPlayModeChange(PlayMode playMode) {
//更新播放模式并修改UI
        mCurrentModel = playMode;
        //更新pop里的播放模式
        mSobPopWindow.updatePlayMode(mCurrentModel);
        updatePlayModeBtnImg();

    }

    /**
     * 进度切换
     *
     * @param currentProgress
     * @param total
     */
    @Override
    public void onProgressChange(int currentProgress, int total) {
        mMSeekBar.setMax(total);
        //判断时间长度来决定调用那个时间格式
        if (total > 60 * 60 * 1000) {
            totalDuration = mHourFormat.format(total);
        } else {
            totalDuration = mMinFormat.format(total);
        }
        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration + "");
        }
        //当前进度
        setCurrentProgress(currentProgress, mUserCollter);

        if (!mIsUserTouchProgressBar) {
            mMSeekBar.setProgress(currentProgress);
        }
    }

    //设置进度条
    private void setCurrentProgress(int currentProgress, boolean flag) {
        if (currentProgress > 60 * 60 * 1000) {
            currentPosition = mHourFormat.format(currentProgress);
        } else {

            currentPosition = mMinFormat.format(currentProgress);
        }
        if (mCurrentPosition != null && !flag) {
            mCurrentPosition.setText(currentPosition + "");
        }
    }

    /**
     * 广告加载
     */
    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinishaed() {

    }


    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        LogUtils.d(TAG, "playIndex--->" + playIndex);
        this.mTrackTitletemp = track.getTrackTitle();
//        mPlayIndex =playIndex;
        LogUtils.d(TAG, "list -------------->"+mPlayIndex );
        if (mTrackTitle != null) {
            mTrackTitle.setText(mTrackTitletemp);
        }
        //当节目改变时，就获取到当前播放的位置
//        当前节目改变以后修改图片
        if (mTrackCover != null) {
            mTrackCover.setCurrentItem(playIndex, true);
        }
        //设置播放列表当前的位置
        if (mSobPopWindow != null) {
            mSobPopWindow.setCurrentIndex(playIndex);
        }
    }



}
